package com.yanqu.road.server.manger;

import com.yanqu.road.entity.enums.eServerGroup2Type;
import com.yanqu.road.entity.servercenter.ServerGroup2;
import com.yanqu.road.logic.bussiness.servercenter.ServerBussiness;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.manger.plugin.ManagerReloadListener;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ServerGroup2Mgr extends TempMgr {

    // Map<类型，分组，区服>
    private static Map<Integer, Map<Integer, ServerGroup2>> groupMap = new ConcurrentHashMap<>();

    private static ManagerReloadListener managerReloadListener;

    public static ServerGroup2 getServerGroup2(eServerGroup2Type group2Type, int groupId) {
        Map<Integer, ServerGroup2> group2Map = groupMap.get(group2Type.getValue());
        if (group2Map == null) {
            return null;
        }
        return group2Map.get(groupId);
    }

    public static ServerGroup2 getServerGroup2(eServerGroup2Type group2Type, long serverId) {
        Map<Integer, ServerGroup2> group2Map = groupMap.get(group2Type.getValue());
        if (group2Map == null) {
            return null;
        }
        for (ServerGroup2 value : group2Map.values()) {
            if (value.getServerList().contains(serverId)) {
                return value;
            }
        }
        return null;
    }

    public static int getServerGroup2Id(eServerGroup2Type group2Type, long serverId) {
        ServerGroup2 serverGroup2 = getServerGroup2(group2Type, serverId);
        return serverGroup2 == null ? 0 : serverGroup2.getGroupId();
    }

    public static void reloadServerGroup() {
        groupMap = ServerBussiness.getAllServerGroup2Map();
        notifyReload();
    }

    public static Map<Integer, ServerGroup2> getGroupMap(eServerGroup2Type group2Type) {
        return groupMap.containsKey(group2Type.getValue()) ? groupMap.get(group2Type.getValue()) : new ConcurrentHashMap<>();
    }

    public static void addReloadListener(ManagerReloadListener reloadListener) {
        managerReloadListener = reloadListener;
    }

    private static void notifyReload() {
        if (null != managerReloadListener) {
            managerReloadListener.notifyReload();
        }
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        reloadServerGroup();
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
